package com.um.jdy.ykc.utils;

import java.util.Calendar;
import java.util.Date;

/**
 * 云快充时间转换算法
 *
 * @author 甘天伟
 * @since 2022/7/7
 * 版权所有 广州优匠科技有限公司
 */
public class YkcTimeUtil {

    public static Date toDate(byte[] bytes) {
        int milliseconds = ((bytes[1] & 0xff) * 256) + (bytes[0] & 0xff);
        // 位于 0011 1111
        int minutes = bytes[2] & 0x3f;
        // 位于 0001 1111
        int hours = bytes[3] & 0x1f;
        // 位于 0001 1111
        int days = bytes[4] & 0x1f;
        // 位于 0000 1111
        int months = bytes[5] & 0x0f;
        // 位于 0111 1111
        int years = bytes[6] & 0x7f;

        final Calendar time = Calendar.getInstance();
        time.set(Calendar.SECOND, 0);
        time.set(Calendar.MILLISECOND, milliseconds);
        time.set(Calendar.MINUTE, minutes);
        time.set(Calendar.HOUR_OF_DAY, hours);
        time.set(Calendar.DAY_OF_MONTH, days);
        time.set(Calendar.MONTH, months - 1);
        time.set(Calendar.YEAR, years + 2000);

        return time.getTime();
    }

    public static byte[] toBytes(Date date) {
        byte[] result = new byte[7];

        Calendar time = Calendar.getInstance();
        time.setTime(date);
        int milliseconds = time.get(Calendar.SECOND) * 1000 + time.get(Calendar.MILLISECOND);

        result[0] = (byte) (milliseconds % 256);
        result[1] = (byte) (milliseconds / 256);
        result[2] = (byte) time.get(Calendar.MINUTE);
        result[3] = (byte) time.get(Calendar.HOUR_OF_DAY);
        result[4] = (byte) time.get(Calendar.DAY_OF_MONTH);
        result[5] = (byte) (time.get(Calendar.MONTH) + 1);
        result[6] = (byte) (time.get(Calendar.YEAR) % 100);

        return result;
    }
}
